package com.oa.controller;


import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oa.bean.SeriesPie;
import com.oa.service.StatisticalReportService;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

@Controller
public class ViewChartController {

	@Autowired
	StatisticalReportService statisticalReportService;
	
	@RequestMapping("getViewChart")
	@ResponseBody
	public Map<String,Object> getViewChart(){
		Map<String,Object> map = statisticalReportService.getPiechart();		
		return map;
	}
	
	//获取Excel表格
	@RequestMapping("getDeptExcel")
	public void createExcel(HttpServletResponse response){
		try {
			//获取响应的输出流
			OutputStream out = response.getOutputStream();
			//设置下载的文件类型
			response.setContentType("application/vnd.ms-excel");
			//设置下载文件的文件名
			response.setHeader("Content-Disposition","attachment; filename="+new String(("部门公文统计.xls").getBytes(), "ISO-8859-1"));
			//创建一个工作薄对象
			WritableWorkbook book = Workbook.createWorkbook(out);
			//创建一个或多个工作表，指定工作薄选项卡的名称，以及工作表索引的位置
			WritableSheet sheet1 = book.createSheet("abc", 0);
			//创建一个字体对象 封装指定的字体
			WritableFont font = new WritableFont(WritableFont.createFont("黑体"), 18);
			WritableFont font2 = new WritableFont(WritableFont.createFont("楷体"), 14);
			font.setColour(Colour.GREEN);
			//创建一个单元格对象 封装指定的格式
			WritableCellFormat wcTitle = new WritableCellFormat();
			WritableCellFormat wcTitle2 = new WritableCellFormat();
			wcTitle2.setFont(font2);
			wcTitle.setFont(font);
			wcTitle.setAlignment(Alignment.CENTRE); //居中
			//向Excel中添加数据
			sheet1.addCell(new Label(0,0,"公文信息",wcTitle));
			sheet1.mergeCells(0, 0, 1, 0);
			sheet1.addCell(new Label(0, 1, "部门名称",wcTitle2));
			sheet1.addCell(new Label(1, 1, "次数",wcTitle2));
			Map<String,Object> map =  statisticalReportService.getPiechart();
			@SuppressWarnings("unchecked")
			List<SeriesPie>list = (List<SeriesPie>) map.get("seriesList");
			System.out.println(list);
			int i = 0;
			for(SeriesPie pid: list){
				sheet1.addCell(new Label(0,(i+2), pid.getName(),wcTitle2));
				sheet1.addCell(new Number(1,(i+2), pid.getValue(),wcTitle2));
				i++;
			}
			book.write();
			book.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
